import json
import uuid

import time
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QFileDialog

import cache
from dao.commonDao import ChatMsg
from protoc.command import Command
from protoc import IMProto_pb2

class MsgAction(QObject):

    receiveMsgNotifySignal = pyqtSignal(str)
    ackMsgNotifySignal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.receiveMsgNotifySignal.connect(self.receiveMsgNotify)
        self.ackMsgNotifySignal.connect(self.ackMsgNotify)

    def receiveMsgNotify(self,msg):
        pass

    def ackMsgNotify(self,msg):
        pass

    @pyqtSlot(str)
    def sendMsg(self,msg):
        '''
        本地查询某个用户信息
        :param userId:
        :return:
        '''
        msgD = json.loads(msg)

        sendTime = int(round(time.time() * 1000))

        #保存到数据库
        chatMsg = ChatMsg();
        chatMsg.msgId = msgD['msgId']
        chatMsg.status = 1
        chatMsg.senderId = cache.Cache.userInfo['id']
        chatMsg.time = sendTime
        chatMsg.msgBody = msgD['msgBody']
        chatMsg.senderName = cache.Cache.userInfo['username']
        chatMsg.msgType = msgD['msgType']
        chatMsg.seqId = 0;
        chatMsg.sessionId = msgD['sessionId']
        chatMsg.sessionType = msgD['sessionType']

        cache.Cache.dao.saveMsg(chatMsg)

        from tcp.tcpClient import Package
        pack = Package()
        pack.receiverId = msgD['receiverId']
        pack.ack = 1
        pack.cmd = Command.ChatMsg
        chatMsg = IMProto_pb2.ChatMsg()
        chatMsg.msgId = msgD['msgId']
        chatMsg.msgType = msgD['msgType']
        chatMsg.msgBody = msgD['msgBody']
        chatMsg.sessionId = msgD['sessionId']
        chatMsg.sessionType = msgD['sessionType']
        chatMsg.senderId = cache.Cache.userInfo['id']
        chatMsg.senderName = cache.Cache.userInfo['username']
        chatMsg.time = sendTime

        msgBody = chatMsg.SerializeToString()
        pack.msgBody = msgBody
        from tcp.tcpClient import TcpClient
        TcpClient.getInstance().send(pack)

    def noticeNewMsg(self,msg):
        self.receiveMsgNotifySignal.emit(json.dumps(msg))

    def ackMsg(self,ack):
        self.ackMsgNotifySignal.emit(json.dumps(ack))

    @pyqtSlot()
    def openFileSelect(self):
        fileName,fileType = QFileDialog.getOpenFileName(cache.Cache.app.mainView,'选择图片','/','img (*.jpg *.jpeg *.gif *.png)')
        print(fileName)
        return fileName
